//
//  UserCoverGroundViewController.m
//  CheekiOS
//
//  Created by mac on 2017/6/15.
//  Copyright © 2017年 mac. All rights reserved.
//

#import "UserCoverGroundViewController.h"
#import "SDWeiXinPhotoContainerView.h"
#import "MJPhotoBrowser.h"

@interface UserCoverGroundViewController ()<UIImagePickerControllerDelegate, UINavigationControllerDelegate,CAAnimationDelegate,MJPhotoBrowserDelegate>{
    UIView *background;

}

@property (nonatomic, strong) UIImageView *imageBtn;
@property (nonatomic, strong) NSMutableArray *imageArray;
@property (nonatomic, strong) MJPhotoBrowser *BrowSerPhoto;
@end

@implementation UserCoverGroundViewController



- (void)viewDidLoad {
    [super viewDidLoad];
    [self setNavgationBarHiddenNo];
    self.title = @"选择封面";

    CGFloat imageW = (KScreenWidth - 48)/3;
    CGFloat imageK = 12;
    CGFloat imageHK = 10;
    
    _imageArray = [NSMutableArray new];
    
    for (int i = 0; i < 12 ; i++) {
        
        NSString *str = [NSString stringWithFormat:@"image_ueserback_%d",i];
        [_imageArray addObject:str];
    }
    
    for (int i = 0; i<12; i++) {
        _imageBtn = [UIImageView new];
        _imageBtn.frame =  CGRectMake(imageK+((i%3)*(imageK+imageW)), imageHK+((i/3)*(imageW+imageHK) ), imageW, imageW);
    
        _imageBtn.tag = i;
        
        _imageBtn.image = [UIImage imageNamed:_imageArray[i]];
        
        _imageBtn.contentMode = UIViewContentModeScaleToFill;
        _imageBtn.userInteractionEnabled = YES;
        [_imageBtn addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(photoTap:)]];

        [self.view addSubview:_imageBtn];
    }
    
    
    UIButton *btnImg = [UIButton buttonWithType:UIButtonTypeCustom];
    [btnImg addTarget:self action:@selector(getPhotosAlert) forControlEvents:UIControlEventTouchUpInside];
    [btnImg setTitle:@"自定义封面" forState:UIControlStateNormal];
    [btnImg setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    
    btnImg.frame = CGRectMake(24, _imageBtn.bottom+34, KScreenWidth-48, 50);
    btnImg.backgroundColor = Colorbackground;
    btnImg.layer.cornerRadius=25;
    
    [self.view addSubview:btnImg];
    
}

- (void)photoTap:(UITapGestureRecognizer *)recognizer{

    
    NSInteger count = _imageArray.count;
    NSMutableArray *photos = [NSMutableArray arrayWithCapacity:count];
    // 1.封装图片数据
    
        for (int i = 0; i<count; i++) {
            //公开相册有数据
            
            
            MJPhoto *photo = [[MJPhoto alloc] init];
            photo.image = [UIImage imageNamed:_imageArray[i]];
            photo.srcImageView = self.view.subviews[i];
            
            [photos addObject:photo];
        
    }
    
    // 2.显示相册
    _BrowSerPhoto = [[MJPhotoBrowser alloc] init];
    _BrowSerPhoto.photos = photos; // 设置所有的图片
    
    _BrowSerPhoto.currentPhotoIndex = recognizer.view.tag; // 弹出相册时显示的第一张图片是？
    [_BrowSerPhoto show];
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame =CGRectMake(25,self.view.height-40, KScreenWidth-50, 50);
    [btn setTitle:@"设为封面" forState:UIControlStateNormal];
    btn.layer.cornerRadius=25;
    btn.tag = recognizer.view.tag;
    btn.backgroundColor = Colorbackground;
    [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];

    [btn addTarget:self action:@selector(imageUpdateImageStr:) forControlEvents:UIControlEventTouchUpInside];
    
    [_BrowSerPhoto.view addSubview:btn];
    
}

- (void)imageUpdateImageStr:(UIButton *)imageStr{

    UIImage *img = [UIImage imageNamed:[NSString stringWithFormat:@"image_ueserback_%ld",(long)imageStr.tag]];
    
    [HcardHttpmanager upLoadPhotosWithFile:img WithBelong:@"photo" WithToAublum:KToAublumNO WithAlbumId:nil success:^(id sucess) {
        [SVProgressHUD dismiss];
        if(sucess){
            NSDictionary *dict = @{
                                   @"uid":[HQHttpManager getUserId],
                                   @"background":sucess
                                   };
            [self updateUser:dict];
        }else{
            [SVProgressHUD showErrorWithStatus:@"上传失败!"];
        }
    } failure:^(NSError *error) {
        [SVProgressHUD dismiss];
        [SVProgressHUD showErrorWithStatus:@"上传失败!"];
    }];
    [SVProgressHUD showWithStatus:@"正在上传"];

    

}
#pragma mark - getPhotosAlert
-(void)getPhotosAlert{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"请选择图片" message:nil preferredStyle:UIAlertControllerStyleActionSheet];

    [alert addAction:[UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UIImagePickerController *picekerVc = [[UIImagePickerController alloc] init];
        picekerVc.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        
        picekerVc.delegate = self;
        [self presentViewController:picekerVc animated:YES completion:nil];
        
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }]];
    [self presentViewController:alert animated:YES completion:^{
    }];
}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *image = info[UIImagePickerControllerOriginalImage];
    // NSLog(@"获取的图片为：%@",image);
    
        [HcardHttpmanager upLoadPhotosWithFile:image WithBelong:@"photo" WithToAublum:KToAublumNO WithAlbumId:nil success:^(id sucess) {
            [SVProgressHUD dismiss];
            if(sucess){
                NSDictionary *dict = @{
                                       @"uid":[HQHttpManager getUserId],
                                       @"background":sucess
                                       };
                [self updateUser:dict];
            }else{
                [SVProgressHUD showErrorWithStatus:@"上传失败!"];
            }
        } failure:^(NSError *error) {
            [SVProgressHUD dismiss];
            [SVProgressHUD showErrorWithStatus:@"上传失败!"];
        }];
        [self dismissViewControllerAnimated:YES completion:nil];
        [SVProgressHUD showWithStatus:@"正在上传"];


}

#pragma mark - updateUser
-(void)updateUser:(NSDictionary *)dict{
    
    [HcardHttpmanager MakePersionalInfoWithParam:dict success:^(id sucess) {
        if(sucess){
            NSLog(@"设置成功");
            [SVProgressHUD showWithStatus:@"上传成功"];

            [SVProgressHUD dismissWithDelay:1];
            
            [self.BrowSerPhoto.view removeFromSuperview];
            NSString *Str = @"NotificationUserCoverimageUpdate";
            [[NSNotificationCenter defaultCenter] postNotificationName:Str object:nil
             ];
            [self.navigationController popViewControllerAnimated:YES];
        }
    } failure:^(NSError *error) {
        
    }];
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
